package com.zja.servlet;


import com.zja.model.Article;
import com.zja.model.JsonResponse;
import com.zja.service.ArticleService;
import com.zja.service.Impl.ArticleServiceImpl;
import com.zja.util.ServletUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @author JA
 * @date: 2025/5/4
 * description:分页查询文章
 */
@WebServlet("/api/article/search")
public class SearchArticlesServlet extends HttpServlet {
    private final ArticleService articleService = new ArticleServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            Long kbId = Long.parseLong(req.getParameter("kbId"));
            String keyword = req.getParameter("keyword");
            int page = Integer.parseInt(req.getParameter("page"));
            int pageSize = Integer.parseInt(req.getParameter("pageSize"));

            List<Article> articles = articleService.searchArticles(kbId, keyword, page, pageSize);
            int total = articleService.countArticles(kbId, keyword);

            // 封装分页数据
            Map<String, Object> result = new HashMap<>();
            result.put("total", total);
            result.put("items", articles);

            ServletUtil.writeJsonResponse(resp, JsonResponse.success("搜索成功", result));
        } catch (Exception e) {
            e.printStackTrace();
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("搜索失败: " + e.getMessage()));
        }
    }
}
